<script lang="ts" setup>
  import { ref } from "vue";
  import { useRoute } from "vue-router";
  import { userSocketStore } from "@/store/modules/socket";
  import emitter from "@/utils/emitter";

  const socketStore = userSocketStore();
  const route = useRoute();

  const loading = ref(false);
  const message = ref("");
  const messageList = ref<string[]>([]);

  emitter.on("chatMessage", data => {
    messageList.value = [...messageList.value, data.message];
  });

  function onSubmit(values: any) {
    loading.value = true;
    socketStore.sendMessage({
      receiverId: route.query.id as string,
      message: values.message,
      chatType: route.query.chatType as string
    });
    setTimeout(() => {
      loading.value = false;
    }, 200);
  }
</script>

<template>
  <div class="chat">
    <van-nav-bar
      title="聊天"
      fixed
      placeholder
    />
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          type="textarea"
          :rows="4"
          :maxlength="10000"
          show-word-limit
          v-model="message"
          name="message"
          placeholder="请输入你想说的话"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button
          round
          block
          type="primary"
          native-type="submit"
          :loading="loading"
        >
          发送
        </van-button>
      </div>
    </van-form>
    <van-cell-group v-if="messageList && messageList[0]">
      <van-cell
        v-for="(item, index) in messageList"
        :title="index"
        :value="item"
        :key="index"
      />
    </van-cell-group>
  </div>
</template>

<style scoped lang="scss">
  .chat {
    padding-top: 15px;
  }
</style>
